<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app;

use app\madmin\model\Configuration;
use OSS\OssClient;
use OSS\Core\OssException;
use think\exception\HttpException;
use think\facade\Db;

class Oss
{

    /**
     * mall端单图片上传
     * @param $path string 本地地址
     * @param $filePath string 远程地址
     * @param $mall_id int
     * @return mixed 远程图片地址
     */
    public function up(string $filePath, string $object, int $mid)
    {
        $config = Db::table('jiecheng_configuration')
            ->where('type', 'oss')
            ->where('mall_id', $mid)
            ->value('configuration');
        $js = json_decode($config, true);
//        if ($js['oss_choice'] == 1) {
//            $saas_config = Db::table('jiecheng_saas_configuration')->where('type', 'oss')->find();
//            $js = json_decode($saas_config['configuration'], true);
//        }
        $is_open = $js['is_open'];
        switch ($js['is_open']) {
            case 1:
                $js = $js['ali'];
                break;
            case 2:
                $js = $js['qcloud'];
                break;
        }
        $res['oss-request-url'] = null;

        try {
            if ($is_open == 1) {
                $is_customize = oss_is_customize($js['endpoint']);
                $ossClient = new OssClient($js['accessKeyId'], $js['accessKeySecret'], $js['endpoint'], $is_customize);
                $res = $ossClient->uploadFile($js['bucket'], $object, $filePath);
            }
            if ($is_open == 2) {

                require dirname(__FILE__) . '/../vendor/cos/autoload.php';
                $cosClient = new \Qcloud\Cos\Client(array(
                    'region' => $js['region'],
                    'schema' => 'http', //协议头部，默认为http
                    'credentials' => array(
                        'secretId' => $js['accessKeySecret'],
                        'secretKey' => $js['accessKeyId']
                    )
                ));
                $result = $cosClient->putObject(array(
                    'Bucket' => $js['bucket'],
                    'Key' => $filePath,
                    'Body' => fopen($object, 'rb')
                ));

                $res['oss-request-url'] = strstr($result["Location"], "/");

                // $res['oss-request-url'] = "https://".$result["Location"];
            }
        } catch (OssException $e) {
            throw new HttpException(HTTP_INVALID, "配置错误！");
        }
        return $res['oss-request-url'];
    }

    public function exists(string $object, int $mid)
    {
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $config = Db::table('jiecheng_configuration')
            ->where('type', 'oss')
            ->where('mall_id', $mid)
            ->value('configuration');
        $js = json_decode($config, true);


        $accessKeyId = $js['accessKeyId'];
        $accessKeySecret = $js['accessKeySecret'];
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = $js['endpoint'];
        // 设置存储空间名称。
        $bucket = $js['bucket'];

        try {
            $is_customize = oss_is_customize($js['endpoint']);
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, $is_customize);
            $exists = $ossClient->doesObjectExist($bucket, $object);
        } catch (OssException $e) {
            throw new HttpException(HTTP_INVALID, $e->getMessage());
        }
        return $exists;
    }

    /**
     * saas端单图片上次
     * @param $path string 本地地址
     * @param $filePath string 远程地址
     * @return string|null 图片完整地址
     * @throws
     */
    public function saasUp($path, $filePath)
    {
        $saas_config = Db::table('jiecheng_saas_configuration')->where('type', 'oss')->find();
        $saas_js = json_decode($saas_config['configuration'], true);
        $res['oss-request-url'] = null;
        if (isset($saas_js['is_open']) && $saas_js['is_open'] > 0) {
            $is_open = $saas_js['is_open'];
            try {
                // 阿里云oss
                if ($is_open == 1) {
                    $config = $saas_js['ali'];
                    $is_customize = oss_is_customize($config['endpoint']);
                    $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint'], $is_customize);
                    $res = $ossClient->uploadFile($config['bucket'], $filePath, $path);
                }
                // 腾讯云cos
                if ($is_open == 2) {
                    $config = $saas_js['qcloud'];
                    require dirname(__FILE__) . '/../vendor/cos/autoload.php';
                    $cosClient = new \Qcloud\Cos\Client(array(
                        'region' => $config['region'],
                        'schema' => 'http', //协议头部，默认为http
                        'credentials' => array(
                            'secretId' => $config['accessKeySecret'],
                            'secretKey' => $config['accessKeyId']
                        )
                    ));
                    $result = $cosClient->putObject(array(
                        'Bucket' => $config['bucket'],
                        'Key' => $filePath,
                        'Body' => fopen($path, 'rb')
                    ));
                    $res['oss-request-url'] = "https://" . $result["Location"];
                }
            } catch (OssException $e) {
                throw new HttpException(HTTP_INVALID, "配置错误！");
            }
        }
        return $res['oss-request-url'];
    }
}